package com.qxsx.midi.activity.personal;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qxsx.midi.R;
import com.qxsx.midi.activity.base.BaseActivity;
import com.qxsx.midi.config.AppContext;
import com.qxsx.midi.utils.CustomProgress;
import com.qxsx.midi.utils.MyNet;
import com.qxsx.midi.utils.SPUtils;
import com.qxsx.midi.utils.callBackJsonArray;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Pattern;

/**
 * Created by LYJ on 2015/9/8.
 */
public class PersonalEditPhoneNumActivity extends BaseActivity implements View.OnClickListener{
    private CustomProgress customProgress;

    private RelativeLayout rl_mess,rl_name,rl_email,rl_position,rl_password,rl_phonenum;
    private LinearLayout ll_back,ll_save;
    private Button bt_send;
    private EditText ed_phone,ed_code;
    Intent intent = new Intent();
    // 可以验证
    boolean canChecking = true;
    // 验证用的Timer
    Timer timer;
    // 间隔时间
    final int spacing = 60;
    // 剩余时间
    int lastTime;
    private String verificationCode="";//验证码
    private String userid;
    Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_phone);
        setTitle("修改手机号码");
        setNavBtn(R.mipmap.back, null, 0, "保存");
        ed_phone = (EditText)findViewById(R.id.ed_pass_phone);
        ed_code = (EditText)findViewById(R.id.ed_pass_code);
        bt_send = (Button)findViewById(R.id.bt_pass_send);

        bt_send.setOnClickListener(this);
        userid = (String) SPUtils.get(AppContext.getContext(), "user_id", " ");
        String userphone= (String) SPUtils.get(AppContext.getContext(), "user_phone", "");
        if(userphone==null){
            userphone="";
        }
        ed_phone.setText(userphone);

    }

    @Override
    protected void HandleTitleBarEvent(TitleBar component, View v) {
        switch (component) {
            case LEFT:
                finish();
                break;
            case RIGHT:
                final String num= ed_phone.getText().toString().trim();
                if(num!=null&&num!=""){
                    if(!isMobileNO(num)){
                        showToast("手机号码不正确");
                        return;
                    }
                }
                final String Code= ed_code.getText().toString().trim();
                if (!Code.equals(verificationCode)) {
                    showToast("验证码不正确");
                    return;
                }
                LayoutInflater layout = LayoutInflater.from(AppContext.getContext());
                View view = layout.inflate(R.layout.dialog_buy_finish, null);
                dialog = new AlertDialog.Builder(PersonalEditPhoneNumActivity.this).create();
                TextView tv_zhifu = (TextView)view.findViewById(R.id.tv_zhifu);
                tv_zhifu.setText("是否保存？");
                Button btn_see = (Button) view.findViewById(R.id.btn_see);
                btn_see.setText("是");
                Button btn_clance = (Button) view.findViewById(R.id.btn_cancel);
                btn_clance.setText("否");
                btn_clance.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        dialog.dismiss();

                    }
                });
                btn_see.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toSave(num);
                        dialog.dismiss();
                    }
                });
                DisplayMetrics dm = new DisplayMetrics();
                PersonalEditPhoneNumActivity.this.getWindowManager().getDefaultDisplay().getMetrics(dm);
                int x = dm.widthPixels;// 屏幕的宽
                int y = dm.heightPixels;// 屏幕的高
                dialog = new Dialog(PersonalEditPhoneNumActivity.this, R.style.dialog_finish);
                dialog.getWindow().setLayout((int) (x / 2.2), (int) (y / 1.8));
                dialog.show();
                dialog.setContentView(view);
                dialog.setCancelable(false);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(timer != null)
            timer.cancel();
    }


    private  void toSave(final String str){

        customProgress = CustomProgress.show(PersonalEditPhoneNumActivity.this, "正在提交，请稍后....", true, null);

        JSONArray array = new JSONArray();
        JSONObject object = new JSONObject();
        try {
            object.put("user_id",userid);
            object.put("phone", str);
            object.put("code", verificationCode);
            array.put(object);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MyNet.doPostJsonArray("113", array, new callBackJsonArray() {
                    @Override
                    public void run(Object code, Object message, JSONArray array) {
                        // Log.e("-------------",code.toString());
                       if (array == null) {
                            Log.w("array", array + "");
                            return;
                        } else {
                            SPUtils.put(AppContext.getContext(), "user_phone", str);
                            Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                            finish();
                        }
                        customProgress.dismiss();
                    }
                }

        );

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bt_pass_send:
                //发送验证码
                String phonenum= ed_phone.getText().toString().trim();
                if(phonenum!=null&&phonenum!=""){
                    if(!isMobileNO(phonenum)){
                        showToast("手机号码不正确");
                        return;
                    }
                }else{
                    showToast("手机号码不能为空");
                    return;
                }
                if(canChecking)    // 如果可以获取验证码
                {
                    canChecking = false;
                    timer = new Timer();
                    lastTime = spacing;
                   // bt_send.setBackgroundResource(R.drawable.pub_black_round_gray_bg);
                    final String oldtxt = bt_send.getText().toString();
                    bt_send.setText(lastTime + "S");
                    bt_send.setTextColor(getResources().getColor(R.color.theme_green));
                    //showToast("验证码1234");
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if(lastTime == 0) // 时间到了
                            {
                                PersonalEditPhoneNumActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        // bt_send.setBackgroundResource(R.drawable.pub_white_round_gray_bg);
                                        bt_send.setText(oldtxt);
                                        bt_send.setTextColor(getResources().getColor(R.color.theme_green));
                                        timer.cancel();
                                        timer = null;
                                        canChecking = true;
                                    }
                                });

                            }
                            else
                            {
                                PersonalEditPhoneNumActivity.this.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        lastTime--;
                                        bt_send.setText(lastTime + "S");
                                    }
                                });

                            }
                        }
                    },1000,1000);
                    final String Code= ed_code.getText().toString().trim();
                    JSONArray array = new JSONArray();
                    JSONObject object = new JSONObject();
                    try {
                        object.put("phone", phonenum);
                        array.put(object);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    MyNet.doPostJsonArray("107", array, new callBackJsonArray() {
                                @Override
                                public void run(Object code, Object message, JSONArray array) {
                                    //  Log.e("-------------", code.toString());
                                    if (!code.toString().equals("200")) {
                                        Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();
                                    } else if (array == null) {
                                        Log.w("array", array + "");
                                        return;
                                    } else {
                                        try {
                                            JSONObject jsonObject = array.getJSONObject(0);
                                            verificationCode = jsonObject.getString("validate_num");
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                        Toast.makeText(AppContext.getContext(), message.toString(), Toast.LENGTH_SHORT).show();

                                    }
                                }
                            }

                    );
                }
                else            // 不可以获取验证码
                {
                    return;
                }
                break;
        }
    }

    private void showToast(String s) {
        Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
    }

    public static boolean isMobileNO(String mobiles){
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        return p.matcher(mobiles).matches();
    }

    public static int dip2px(Context context, float dipValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue * scale + 0.5f);
    }

    // 像素转 dpi
    public static int px2dip(Context context, float pxValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue / scale + 0.5f);
    }
}
